package com.bang.study.config;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.FileType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;


public class MyBatisPlusCodeGenerator {


    private  String url;

    private  String driverName;

    private  String username;

    private  String password;

    private  String projectPath;




    /**
     * @Desc: 项目（绝对）根路径
     * @Author: shitao
     * @Date: 2019/10/11 21:11
     * @Param: projectPath
     * @Return: <p></p>
     */
    public MyBatisPlusCodeGenerator(String projectPath) throws Exception {
        if (null == projectPath || "".equals(projectPath)) {
            throw new Exception("配置文件地址异常！");
        }
        this.projectPath = projectPath + File.separator;
        Properties propObj = new Properties();
        propObj.load(new FileInputStream(this.projectPath + "src" + File.separator + "main" + File.separator + "resources" + File.separator + File.separator + "jdbc.properties"));
        url = propObj.getProperty("jdbc.url");
        driverName = propObj.getProperty("jdbc.driver");
        username = propObj.getProperty("jdbc.username");
        password = propObj.getProperty("jdbc.password");
    }

    private String baseController = "com.bang.framework.base.response.BaseController";

    /**
     * 代码生成
     *
     * @param author   作者
     * @param tables   表名（多个以逗号隔开）,该值为空生成全部表
     * @param packages 包路径
     */
    public void generator(String author, String tables, String packages) {
        //代码生成器
        AutoGenerator generator = new AutoGenerator();

        //全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(projectPath + File.separator + "src" + File.separator + "main" + File.separator + "java");
        gc.setAuthor(author);
        gc.setOpen(false);
        //默认不覆盖，如果文件存在，将不会再生成，配置true就是覆盖
        gc.setFileOverride(true);
        gc.setIdType(IdType.INPUT);

        //数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(url);
        dsc.setDriverName(driverName);
        dsc.setUsername(username);
        dsc.setPassword(password);

        //包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(packages);
        pc.setController("controller");

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null);


        //配置策略
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//        strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setSuperControllerClass(baseController);
        if (!StringUtils.isEmpty(tables)) {
            strategy.setInclude(tables.split(","));//设置表名
        }
//        strategy.setSuperEntityColumns("id");
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");

        //自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {

            }
        };
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                checkDir(filePath);
                File file = new File(filePath);
                if (file.exists()) {
                    if (FileType.ENTITY == fileType) {
                        return true;
                    } else {
                        return false;
                    }
                }
                return true;
            }
        });

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return projectPath + "src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);


        generator.setGlobalConfig(gc);
        generator.setDataSource(dsc);
        generator.setPackageInfo(pc);
        generator.setTemplate(templateConfig);
        generator.setTemplateEngine(new FreemarkerTemplateEngine());
        generator.setStrategy(strategy);
        generator.setCfg(cfg);
        generator.execute();
    }
}
